package logic

import (
	"2210a/practice/models/mysql"
	"2210a/practice/models/redisinit"
	"context"
	"encoding/json"
	"strconv"
	"time"

	"2210a/practice/practicerpc/internal/svc"
	"2210a/practice/practicerpc/practicerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopListLogic {
	return &ShopListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShopListLogic) ShopList(in *practicerpc.ShopListRequest) (*practicerpc.ShopListResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	if page <= 0 {
		page = 1
	}
	pageSize := in.PageSize
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize
	key := "ShopList" + strconv.Itoa(int(offset))
	var product []mysql.Product
	get := redisinit.ClientRedis.Get(key)

	if get.Val() == "" {
		mysql.Db.Debug().Offset(int(offset)).Limit(int(pageSize)).Where("shop_name LIKE ?", "%"+in.ShopName+"%").
			Order("shop_bank desc").Order("created_at desc").Find(&product)
		marshal, _ := json.Marshal(&product)
		redisinit.ClientRedis.Set(key, marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get.Val()), &product)
	}

	var slice []*practicerpc.ShopList
	for _, v := range product {
		list := practicerpc.ShopList{
			Id:             int64(v.ID),
			UserId:         v.UserId,
			Avatar:         v.Avatar,
			ShopName:       v.ShopName,
			ShopNavigation: v.ShopNavigation,
			ShopLabel:      v.ShopLabel,
			ShopBank:       v.ShopBank,
			SalesVolume:    v.SalesVolume,
			Status:         v.Status,
		}
		slice = append(slice, &list)
	}
	return &practicerpc.ShopListResponse{List: slice}, nil
}
